<?php

namespace app\common\model;

use think\Model;


class UserAddress extends Model
{

    // 表名
    protected $name = 'user_address';

    // 隐藏字段
    protected $hidden = ['user_id'];
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
    ];

    /**
     * 获取用户地址列表
     */
    public static function getList($user_id)
    {
        return self::where(['user_id' => $user_id])->order('is_default DESC, id DESC')->select();
    }

    /**
     * 地址详情
     */
    public static function getDetail($params = [])
    {
        $where      = isset($params['where']) ? $params['where'] : ['id' => -1];
        $order      = isset($params['order']) ? $params['order'] : 'id DESC';
        return self::where($where)->order($order)->find();
    }

    /**
     * 新增以及编辑地址
     */
    public static function setSave($params = [])
    {
        if (empty($params['user_id'])) {
            return false;
        }

        self::startTrans();

        if ($params['is_default'] == 1) {
            self::where(['user_id' => $params['user_id']])->update(['is_default' => 0]);
        }

        if (isset($params['id'])) {
            if (!self::where(['id' => $params['id'], 'user_id' => $params['user_id']])->update($params)) {
                self::rollback();
                return false;
            }
        } else {
            if (!self::insert($params)) {
                self::rollback();
                return false;
            }
        }

        self::commit();
        return true;
    }
}
